import java.util.ArrayList;

public class MergeKLists {
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        // 归并排序
        if (lists.size() == 0) {
            return null;
        }
        return merge(lists, 0, lists.size()-1);
    }

    private ListNode merge(ArrayList<ListNode> lists, int left, int right) {
        if (left >= right) {
            return lists.get(left);
        }
        int mid = left + (right - left) / 2;
        ListNode leftListNode = merge(lists, left, mid);
        ListNode rightListNode = merge(lists, mid+1, right);
        ListNode cur1 = leftListNode;
        ListNode cur2 = rightListNode;
        ListNode phead = new ListNode(-1);
        ListNode cur = phead;
        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            } else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (cur1 != null) {
            cur.next = cur1;
        }
        if (cur2 != null) {
            cur.next = cur2;
        }
        return phead.next;
    }

    static class ListNode {
        int val;
        ListNode next = null;
        public ListNode(int val) {
        this.val = val;
        }
    }

    public static void main(String[] args) {
        MergeKLists m = new MergeKLists();
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(4);
        l2.next = new ListNode(5);
        l2.next.next = new ListNode(6);
        ListNode l3 = new ListNode(7);
        ArrayList<ListNode> lists = new ArrayList<>();
        lists.add(l1);
        lists.add(l2);
        m.mergeKLists(lists);
        System.out.println(777);
    }
}
